package com.orangelife.service.base.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.orangelife.service.base.dao.JdbcGenericDao;

public abstract class MybaitsGenericDao<T, PK extends Serializable> extends
		SqlSessionDaoSupport implements JdbcGenericDao<T, PK> {

	public static Logger logger = Logger.getLogger(MybaitsGenericDao.class);
	private Class<T> entityClass;

	public Class<T> getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Resource(name = "jdbcTemplate")
	public JdbcTemplate jdbcTemplate;

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Resource(name = "sqlSession")
	private SqlSessionTemplate sqlSessionTemplate;

	@Resource(name = "sqlSession")
	public void setInjectSessionFactory(SqlSessionTemplate sessionFactory) {

		super.setSqlSessionTemplate(sessionFactory);
	}

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		MybaitsGenericDao.logger = logger;
	}

	public SqlSessionTemplate getSqlSessionTemplate() {
		return sqlSessionTemplate;
	}

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}

	@Override
	public T save(String methodPath, T entity) {
		Assert.notNull(entity);
		sqlSessionTemplate.insert(methodPath, entity);
		return entity;
	}

	@Override
	public T update(String methodPath, T entity) {
		Assert.notNull(entity);
		sqlSessionTemplate.update(methodPath, entity);

		return entity;
	}

	@Override
	public void delete(String methodPath, T entity) {

		Assert.notNull(entity);
		sqlSessionTemplate.delete(methodPath, entity);

	}

	@Override
	public List<T> findAll(String methodPath) {
		return sqlSessionTemplate.selectList(methodPath);

	}

	@Override
	public T findById(String methodPath, PK ID) {
		Assert.notNull(ID);
		return sqlSessionTemplate.selectOne(methodPath, ID);
	}

	@Override
	public void deleteByID(String methodPath, PK ID) {
		Assert.notNull(ID);
		sqlSessionTemplate.delete(methodPath, ID);

	}

	@Override
	public PageInfo<T> findByPage(List<T> result, int pageNo, int pageSize) {
		PageHelper.startPage(pageNo, pageSize);
		PageInfo<T> page = new PageInfo<T>(result);
		return page;
	}

}
